/**
 * Created by udi on 2016/11/28.
 */

'use strict'

let mor = require("../libs/mongo/mongoHelper");
let querystring = require('querystring');
let dbr = require("../libs/mysql/mysqlHelper");
let jv = require("../libs/sys/myHelper").jv;
let http = require('request-promise');


app.use(app.routes.get('/html/store/list', async ctx=> {
  ctx.render('store/list');
}));
app.use(app.routes.get('/html/store/confirm', async ctx=> {
  ctx.render('store/confirm');
}));


app.use(app.routes.get('/html/store/detail', async ctx=> {
  ctx.render('store/detail');
}));

app.use(app.routes.post('/store/detail', async function () {

  var params = querystring.parse(this.req._parsedUrl.query);
  let storeId = params.id;


  //id: 2, logo: "../img/kfc.png", name: "肯德基", remark: "11点前点餐送汤", location: "中关村图书大厦一层", price: "20",

  let store = await dbr.findOne(`select s.*,f.name fuwu_name,f.code fuwu_code
from thwy_store s join thwy_fuwu f on (s.fuwu_id = f.id) 
where s.id=:id`, {id: storeId});
  if (!store) {
    this.msg = "没有数据!";
    return;
  }


  let product = await mor.findOne("Product", {productId: storeId});
  if (!product) {
    this.msg = "没有找到数据!";
    return;
  }
  delete product.details;
  jv.extend(product, store);

  if (product.image) {
    product.image = "/img?url=" + product.image;
  }
  if (product.prices) {
    product.prices.forEach(it => {
      if (it.image) {
        it.image = app.appConfig.imageHost + it.image;
      }
    });
    // for (let i in product.prices) {
    //   product.prices[i].image = app.appConfig.imageHost + product.prices[i].image;
    // }
  }

  this.body = product;
}));

app.use(app.routes.post('/store/list', async ctx => {
  var params = querystring.parse(ctx.req._parsedUrl.query);
  let communityId = params.communityId;
  let fuwuId = params.fuwuId;

  if (!communityId) {
    ctx.msg = "找不到小区ID";
    return;
  }

  if (!fuwuId) {
    ctx.msg = "找不到服务ID";
    return;
  }

  jv.log("当前登录用户：" + (ctx.session.user && ctx.session.user.username));

  let results = await dbr.find(`select * from thwy_store 
where community_Id=:communityId and fuwu_id=:fuwuId and del_flag=0`,
    {communityId: communityId, fuwuId: fuwuId});

  if (!results || !results.length) {
    ctx.body = [];
    return;
  }

  results.forEach(it => {
    if (it.image) {
      it.image = app.appConfig.imageHost + it.image;
    }
  });

  ctx.body = results;
}));


let validateFee = async function (postJson) {
  let computeItem = function () {
    this["单价"] = this.price;
    this["数量"] = this.number;
    this["名称"] = this.name;
    this["分类"] = this.category;
    this["单位"] = this.Unit;
    this["费用"] = this.fee = jv.getInt(this.price) * jv.getInt(this.number);

    if (!this.number) return;
    if (!this.feeFormula) return;

    let feeScript = `var result = (function(){
var 单价=this.单价,数量=this.数量,名称=this.名称,分类=this.分类,单位=this.单位,费用=this.费用; return `
      + this.feeFormula + "}).call(this); if( !jv.isNull(jv.result) ){ this['费用'] = result; this.fee = result;} ";

    return eval("eval(function(){ " + feeScript + "})").call(this);
  }
  let computeTotal = function () {
    let total = 0;
    for (var i = 0, len = this.prices.length; i < len; i++) {
      let item = this.prices[i];
      computeItem.call(item);
      this[item.name] = item;
      total += item.fee;
    }
    this["总费用"] = this.total = total;
    if (!this.totalFormula) return;

    let feeScript = "var 总费用 = this.total; this.total =  " + this.totalFormula + " ;";

    return eval("eval(function(){ " + feeScript + "})").call(this);
  }

  //验证客户端提交的总价格。
  if (!postJson.storeId) return false;
  if (!postJson.prices || !postJson.prices.length) return false;


  for (var i = 0, len = this.prices.length; i < len; i++) {
    let dbItem = this.prices[i];
    dbItem.number = 0;
    let item = postJson.prices.filter(it => it.priceId == dbItem.priceId)[0];
    if (item) {
      dbItem.number = item.number;
    }
  }

  computeTotal.call(this);

  if (this.total != postJson.total) {
    return false;
  }

  return true;
}


app.use(app.routes.post('/store/order', async ctx => {
  if (!ctx.needLogin()) {
    return;
  }

  let json = ctx.req.json;

  let product = await mor.findOne("Product", {productId: json.storeId});
  if (!product) {
    ctx.msg = "找不到商品信息！";
    return;
  }

  if (validateFee.call(product, json) == false) {
    ctx.msg = "验证支付金额不正确！";
    return;
  }

  let storeInfo = await dbr.findOne(`select 
s.*,f.name fuwuName
from thwy_store s
join thwy_fuwu f on ( s.fuwu_id = f.id) 
where s.id=:id`, {id: json.storeId});
  if (!storeInfo) {
    ctx.msg = "找不到商家信息！";
    return;
  }

  if (json.total >= storeInfo.min_price * 100) {
    if (json.freight) {
      ctx.msg = "配送费验证失败";
      return;
    }
  } else if (json.freight != storeInfo.freight) {
    ctx.msg = "配送费不正确";
    return;
  }

  let data = {};
  data.addressId = json.addressId;
  data.details = storeInfo.fuwuName;
  data.totalAmount = json.total / 100 + json.freight / 1;
  data.fuwuId = storeInfo.fuwu_id;
  data.fuwuPrices = [];

  for (let i in product.prices) {
    if (!product.prices[i].number) continue;
    let it = product.prices[i];

    data.fuwuPrices.push({
      id: it.priceId,
      quantity: it.number,
      name: it.name,
      unit: it.unit,
      price: it.price / 100,
      pricePayable: it.fee / 100
    });
  }

  data.freight = json.freight;
  data.storeId = storeInfo.id;

  jv.log("token:" + ctx.session.user_token);
  jv.log("请求数据：" + JSON.stringify(data));

  let res = await jv.post({
    url: app.appConfig.fontHost + "api/order/add?token=" + ctx.session.user_token,
    body: data,
    headers: {"token": ctx.session.user_token}
  });
  if (res.statusCode != 200) {
    jv.log("调用api/order/add:" + res.statusCode);
    ctx.msg = "调用失败";
    return;
  }
  if (res.body.message) {
    ctx.msg = res.body.message;
    return;
  }

  ctx.body = res.body;
}));
